﻿
namespace VMWareLabWorkflowsDataContracts.VMWareLabDetailsDialogControls.ViewModel
{
    using System;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.ComponentModel;
    using System.Windows;
    using Microsoft.TeamFoundation.Build.Client;
    using Microsoft.TeamFoundation.Build.Workflow;
    using Microsoft.TeamFoundation.Build.Workflow.Activities;
    using Microsoft.TeamFoundation.Lab.Workflow.Activities;

    public class BuildDetailsViewModel : INotifyPropertyChanged
    {
        public BuildDetails BuildDetailsVm { get; set; }
        public IBuildDefinition[] BuildDefinitions { get; set; }
        public ObservableCollection<KeyValuePair<string, Uri>> BuildDetails { get; set; }
        public ObservableCollection<PlatformConfiguration> PlatformConfigurations { get; set; }
       
        public IBuildDefinition SelectedBuildDefinition
        {
            get
            {
                return this.selectedBuildDefinition;
            }
            set
            {
                this.selectedBuildDefinition = value;
                this.OnPropertyChanged("SelectedBuildDefinition");
            }
        }

        public KeyValuePair<string, Uri> SelectedBuildDetail
        {
            get
            {
                return this.selectedBuildDetail;
            }
            set
            {
                this.selectedBuildDetail = value;
                this.OnPropertyChanged("SelectedBuildDetail");
            }
        }

        public PlatformConfiguration SelectedPlatformConfiguration
        {
            get
            {
                return this.selectedPlatformConfiguration;
            }
            set
            {
                this.selectedPlatformConfiguration = value;
                this.OnPropertyChanged("SelectedPlatformConfiguration");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        private IBuildServer buildServer;
        private IBuildDefinition selectedBuildDefinition;
        private KeyValuePair<string, Uri> selectedBuildDetail;
        private PlatformConfiguration selectedPlatformConfiguration;
        private string teamProject;

        public BuildDetailsViewModel()
        {
            try
            {
                if (VMWareWizardData.VMWareWizzardDataInstance.VMWareLabWorkflowDetails.BuildDetails == null)
                {
                    VMWareWizardData.VMWareWizzardDataInstance.VMWareLabWorkflowDetails.BuildDetails = new BuildDetails() {IsTeamSystemBuild = true, QueueNewBuild = true};
                }
                this.BuildDetailsVm = VMWareWizardData.VMWareWizzardDataInstance.VMWareLabWorkflowDetails.BuildDetails;
                this.teamProject = VMWareWizardData.VMWareWizzardDataInstance.BuildDefinition.TeamProject;
                this.BuildDetails = new ObservableCollection<KeyValuePair<string, Uri>>();
                this.PlatformConfigurations = new ObservableCollection<PlatformConfiguration>();
                this.GetAllBuildDefinitions();
                this.InitializeBuildDetailsControl();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error initializing build details!", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// Gets all build definitions.
        /// </summary>
        private void GetAllBuildDefinitions()
        {
            var tfs = VMWareWizardData.VMWareWizzardDataInstance.BuildDefinition.BuildServer.TeamProjectCollection;
            tfs.EnsureAuthenticated();
            if (tfs.HasAuthenticated)
            {
                this.buildServer = tfs.GetService(typeof(IBuildServer)) as IBuildServer;
                this.BuildDefinitions = this.buildServer.QueryBuildDefinitions(this.teamProject);
            }
        }

        /// <summary>
        /// Initializes the build details.
        /// </summary>
        private void InitializeBuildDetailsControl()
        {

            foreach (var buildDefinition in this.BuildDefinitions)
            {
                if (buildDefinition.Name.Equals(this.BuildDetailsVm.BuildDefinitionName))
                {
                    this.SelectedBuildDefinition = buildDefinition;
                }
            }
            if (!string.IsNullOrEmpty(this.BuildDetailsVm.BuildDefinitionName))
            {
                this.GetBuildDetails(this.teamProject, this.BuildDetailsVm.BuildDefinitionName);
            }
            
            foreach (var buildDetail in this.BuildDetails)
            {
                if (buildDetail.Value == null)
                {
                    this.SelectedBuildDetail = buildDetail;
                }
                else if (buildDetail.Value.Equals(this.BuildDetailsVm.BuildUri))
                {
                    this.SelectedBuildDetail = buildDetail;
                }
            }
            this.GetBuildSettings();
            foreach (var pc in this.PlatformConfigurations)
            {
                if (this.BuildDetailsVm != null && pc.Configuration.Equals(this.BuildDetailsVm.Configuration.Configuration) && pc.Platform.Equals(this.BuildDetailsVm.Configuration.Platform))
                {
                    this.SelectedPlatformConfiguration = pc;
                }
            }
            //if (this.BuildDetailsVm != null)
            //{
            //    this.SelectedPlatformConfiguration = this.BuildDetailsVm.Configuration;
            //}
        }

        /// <summary>
        /// Gets the build details.
        /// </summary>
        public void GetBuildDetails(string teamProject, string buildDefinitionName)
        {
            this.BuildDetails.Clear();
            var latestBuild = new KeyValuePair<string, Uri>("<Latest>", null);
            this.BuildDetails.Add(latestBuild);
            var bd = this.buildServer.QueryBuilds(teamProject, buildDefinitionName);
            foreach (var buildDetail in bd)
            {
                this.BuildDetails.Add(new KeyValuePair<string, Uri>(buildDetail.BuildNumber, buildDetail.Uri));
            }
            this.SelectedBuildDetail = latestBuild;
        }

        /// <summary>
        /// Gets the build settings.
        /// </summary>
        public void GetBuildSettings()
        {
            if (this.SelectedBuildDefinition == null)
            {
                return;
            }
            BuildSettings buildSettings = null;
            IDictionary<string, object> parameters = WorkflowHelpers.DeserializeProcessParameters(this.SelectedBuildDefinition.ProcessParameters);
            foreach (var parameter in parameters)
            {
                buildSettings = parameter.Value as BuildSettings;
                if (buildSettings != null)
                {
                    break;
                }
            }
            if (buildSettings == null)
            {
                return;
            }
            foreach (var pc in buildSettings.PlatformConfigurations)
            {
                this.PlatformConfigurations.Add(pc);
            }
        }

        #region PropertyChanged
        protected void OnPropertyChanged(string name)
        {
            PropertyChangedEventHandler handler = this.PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(name));
            }
        }
        #endregion

    }
}
